package com.gitee.kamismile.stone.rpc.common.engine;


import com.gitee.kamismile.stone.rpc.common.support.StoneURL;
import com.gitee.kamismile.stone.rpc.common.threadlocal.InternalThreadLocal;

public class StoneRpcContext {

    /**
     * use internal thread local to improve performance
     */
    // FIXME REQUEST_CONTEXT
    private static final InternalThreadLocal<StoneRpcContext> LOCAL = new InternalThreadLocal<StoneRpcContext>() {
        @Override
        protected StoneRpcContext initialValue() {
            return new StoneRpcContext();
        }
    };

    // FIXME RESPONSE_CONTEXT
    private static final InternalThreadLocal<StoneRpcContext> SERVER_LOCAL = new InternalThreadLocal<StoneRpcContext>() {
        @Override
        protected StoneRpcContext initialValue() {
            return new StoneRpcContext();
        }
    };


    private StoneURL chooseStoneURL;

    private boolean remove = true;


    public StoneURL getChooseStoneURL() {
        return chooseStoneURL;
    }

    public void setChooseStoneURL(StoneURL chooseStoneURL) {
        this.chooseStoneURL = chooseStoneURL;
    }

    public boolean canRemove() {
        return remove;
    }

    public void clearAfterEachInvoke(boolean remove) {
        this.remove = remove;
    }


    public static StoneRpcContext getLocalContext() {
        return LOCAL.get();
    }

    public static StoneRpcContext getServerContext() {
        return SERVER_LOCAL.get();
    }

    public static void restoreServerContext(StoneRpcContext oldServerContext) {
        SERVER_LOCAL.set(oldServerContext);
    }

    public static void removeServerContext() {
        SERVER_LOCAL.remove();
    }

    public static void removeContext() {
        removeContext(false);
    }


    public static void removeContext(boolean checkCanRemove) {
        if (LOCAL.get().canRemove()) {
            LOCAL.remove();
        }
    }


}
